package com.watertek.bdcenter.bdcode.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * HttpClient类的工具类
 */
public class HttpClientUtil {
    /**
     * 接口响应正常时间
     */
    private static final int NORMAL_TIME = Integer
            .parseInt(PropertiesUtil.getValue("config/config.properties", "interface.response.normal.time"));

    /**
     * 接口响应警告时间
     */
    private static final int WARNING_TIME = Integer
            .parseInt(PropertiesUtil.getValue("config/config.properties", "interface.response.warning.time"));

    /**
     * HttpClient请求超时
     */
    private static final int HTTPCLIENT_CONNECTION_TIMEOUT = Integer
            .parseInt(PropertiesUtil.getValue("config/config.properties", "httpclient.connection.timeout"));

    /**
     * HttpClient请求超时
     */
    private static final int HTTPCLIENT_CONNECTION_REQUEST_TIMEOUT = Integer
            .parseInt(PropertiesUtil.getValue("config/config.properties", "httpclient.connection.request.timeout"));

    /**
     * HttpClient读取超时
     */
    private static final int HTTPCLIENT_SO_TIMEOUT = Integer
            .parseInt(PropertiesUtil.getValue("config/config.properties", "httpclient.so.timeout"));

    /**
     * 发送GET请求，返回JSON字符串
     * @param url
     * @param key
     * @param address
     * @param city
     * @return
     */
    public static String get(String url, String key, String address, String city) {
        // 拼url字符串
        StringBuffer getUrl=new StringBuffer(url);
        getUrl.append("?key=").append(key);
        if(null!=address && !"".equals(address)){
            getUrl.append("&address=").append(address);
        }
        if(null!=city && !"".equals(city)){
            getUrl.append("&city=").append(city);
        }

        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(HTTPCLIENT_CONNECTION_TIMEOUT).setConnectionRequestTimeout(HTTPCLIENT_CONNECTION_REQUEST_TIMEOUT)
                .setSocketTimeout(HTTPCLIENT_SO_TIMEOUT).build();
        HttpGet httpGet = new HttpGet(getUrl.toString());
        httpGet.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String result= EntityUtils.toString(entity);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
